<template>
  <div>
    <!-- 搜索区域 -->
    <div class="card" style="margin-bottom: 10px">
      <el-input style="width: 240px; margin-right: 10px" v-model="data.name" placeholder="请输入社团名称" />
      <el-button type="primary" @click="load">查询</el-button>
    </div>

    <!-- 表格显示 -->
    <div class="card">
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="id" />
        <el-table-column label="社团名称" prop="name" />
        <el-table-column label="社团介绍" prop="descr" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="info" @click="handleDetail(scope.row)" size="small">查看详情</el-button>
            <el-button 
              v-if="!scope.row.isMember && !scope.row.isPending"
              type="success" 
              @click="handleJoin(scope.row)" 
              size="small"
            >加入社团</el-button>
            <el-button 
              v-else-if="scope.row.isPending"
              type="warning" 
              disabled 
              size="small"
            >审核中</el-button>
            <el-button 
              v-else-if="scope.row.isMember"
              type="danger" 
              @click="handleQuit(scope.row)" 
              size="small"
            >退出社团</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑弹窗表单 -->
    <el-dialog title="社团信息" v-model="data.formVisible" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="100px">
        <el-form-item label="社团名称" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入社团名称" />
        </el-form-item>
        <el-form-item label="介绍" prop="descr">
          <el-input v-model="data.form.descr" type="textarea" placeholder="请输入社团介绍" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情弹窗（保留原弹窗结构，作为备用） -->
    <el-dialog title="社团详情" v-model="data.detailVisible" width="500">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="编号">{{ data.detail.id }}</el-descriptions-item>
        <el-descriptions-item label="社团名称">{{ data.detail.name }}</el-descriptions-item>
        <el-descriptions-item label="社团介绍">{{ data.detail.descr }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import request from '@/utils/request.js';

const router = useRouter();
// 从 localStorage 获取当前用户信息
const user = JSON.parse(localStorage.getItem('xm-pro-user'));

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  detailVisible: false,
  form: {},
  detail: {},
  ids: [],
  rules: {
    name: [{ required: true, message: '请输入社团名称', trigger: 'blur' }]
  }
});

const formRef = ref();

const load = async () => {
  try {
    // 1. 获取社团列表
    const res = await request.get('/club/selectPage', {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        name: data.name
      }
    });
    
    if (res.code === '200') {
      // 2. 获取用户已加入的社团列表
      const joinedRes = await request.get(`/club/selectByStudentId/${user.id}`);
      const joinedClubs = joinedRes.data || [];
      const joinedClubIds = new Set(joinedClubs.map(club => club.id));
      
      // 3. 获取用户待审核的申请列表
      const applicationsRes = await request.get('/club/application/list');
      const pendingApplications = applicationsRes.data?.list || [];
      const pendingClubIds = new Set(pendingApplications
        .filter(app => app.status === '待审核')
        .map(app => app.clubId));
      
      // 4. 更新社团列表，添加状态标记
      data.tableData = res.data.list.map(club => ({
        ...club,
        isMember: joinedClubIds.has(club.id),
        isPending: pendingClubIds.has(club.id)
      }));
      
      data.total = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取社团列表失败');
    }
  } catch (err) {
    console.error('加载社团列表失败:', err);
    ElMessage.error('加载社团列表失败');
  }
};


const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      data.form.id ? updateById() : add();
    }
  });
};

const add = () => {
  request.post('/club/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('新增成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const updateById = () => {
  request.put('/club/updateById', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('更新成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.id);
};

// ✅ 查看详情：跳转到 Clubs-all.vue 并传 clubId
const handleDetail = (row) => {
  if (user.role === 'PRE') {
    router.push({ path: '/president/clubs-all', query: { clubId: row.id } });
  } else {
    router.push({ path: '/student/clubs-all', query: { clubId: row.id } });
  }
};

// ✅ 申请加入：跳转到 RecruitmentApplication.vue 并传 clubId

// 加入社团
const handleJoin = async (row) => {
  try {
    // 先检查是否已经是成员
    const memberRes = await request.get('/club/checkMember', {
      params: {
        clubId: row.id,
        studentId: user.id
      }
    })
    
    if (memberRes.data) {
      ElMessage.warning('您已经是该社团成员')
      return
    }

    // 再检查是否有待审核的申请
    const applicationRes = await request.get('/club/checkApplication', {
      params: {
        clubId: row.id,
        studentId: user.id
      }
    })
    
    if (applicationRes.data) {
      ElMessage.warning('您已经申请过该社团，请等待审核')
      return
    }

    // 如果既不是成员也没有待审核的申请，则弹出确认框
    await ElMessageBox.confirm('确定要加入该社团吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    const res = await request.post('/club/join', {
      clubId: row.id,
      studentId: user.id
    })
    
    if (res.code === '200') {
      ElMessage.success('申请已提交，请等待审核')
      // 立即更新该社团的状态
      row.isPending = true
      row.isMember = false
    } else {
      ElMessage.error(res.msg || '申请失败')
    }
  } catch (err) {
    if (err === 'cancel') {
      // 用户取消操作，不做任何处理
      return
    }
    if (err.response?.data?.msg) {
      ElMessage.warning(err.response.data.msg)
    } else {
      ElMessage.error('申请失败，请稍后重试')
    }
  }
}

// 退出社团
const handleQuit = async (row) => {
  try {
    await ElMessageBox.confirm('确定要退出该社团吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await request.post('/club/quit', {
      clubId: row.id,
      studentId: user.id
    });
    
    if (res.code === '200') {
      ElMessage.success('已退出社团');
      // 立即更新该社团的状态
      row.isMember = false;
      row.isPending = false;
    } else {
      ElMessage.error(res.msg || '退出失败');
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('退出失败');
    }
  }
};

// 页面加载时获取数据
onMounted(() => {
  load();
});

</script>

<style scoped>
.card {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
</style>